package com.example.lib_cache.network.exception;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;


/**
 * 通用异常封装类
 */
public class ApiException extends Exception{

    private static final int SERVER_ERROR = 500;
    private static final int PARSE_ERROR = 501;
    private static final int NETWORK_ERROR = 502;
    private static final int TOKEN_ERROR = 503;

    private String code;
    private String errorMsg;

    public ApiException(String code,String errorMsg){
        this.code = code;
        this.errorMsg = errorMsg;
    }

    public static ApiException handleException(Throwable throwable){
        ApiException ex;
        if(throwable instanceof JsonParseException
                || throwable instanceof JSONException
                || throwable instanceof ParseException){
            JsonParseException jsonParseException = (JsonParseException) throwable;
            jsonParseException.printStackTrace();

            ex = new ApiException(String.valueOf(PARSE_ERROR),"数据解析异常");
            return ex;
        }else if (throwable instanceof ConnectException
                ||throwable instanceof UnknownHostException
                ||throwable instanceof SocketException){
            ex = new ApiException(String.valueOf(NETWORK_ERROR),"网络请求异常");
            return ex;
        }else {
            ex = new ApiException(String.valueOf(SERVER_ERROR),"服务器异常");
            return ex;
        }
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
